package com.ido.news.splashlibrary.model

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.ido.news.splashlibrary.bean.BeanResponse
import com.ido.news.splashlibrary.callback.HttpCallBack
import com.ido.news.splashlibrary.contract.SplashContract
import com.ido.news.splashlibrary.util.CacheHelper
import com.ido.news.splashlibrary.util.Constant
import com.ido.news.splashlibrary.util.SignUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.interceptor.HttpLoggingInterceptor
import com.lzy.okgo.model.Response
import okhttp3.OkHttpClient
import java.io.UnsupportedEncodingException
import java.util.concurrent.TimeUnit
import java.util.logging.Level


class BaseSplashModelImpl : SplashContract.BaseSplashModel() {
    private val tag = "SplashResponse"
    private var cacheHelper: CacheHelper? = null
    private var mVersion: String = ""

    /**
     * 获取服务器数据
     */
    override fun getResponse(context: Context, url: String, channel: String, packageName: String, version: String, callback: HttpCallBack) {
        this.mVersion = version
        try {
            //每个请求都有一个.client()方法可以传递一个OkHttpClient对象，表示当前这个请求将使用外界传入的这个OkHttpClient对象，其他的请求还是使用全局的保持不变。配置什么东西，改个超时时间，加个拦截器什么的统统都是可以
            val builder = OkHttpClient.Builder()
            builder.readTimeout(4, TimeUnit.SECONDS)
            builder.connectTimeout(4, TimeUnit.SECONDS)
            builder.writeTimeout(4, TimeUnit.SECONDS)
            //以下为打印log拦截器
            if (Constant.DEBUG) {
                Log.e(Constant.Tag, "channel:$channel version:$version packageName:$packageName")
                val loggingInterceptor = HttpLoggingInterceptor(Constant.Tag)
                loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY)
                loggingInterceptor.setColorLevel(Level.INFO)
                builder.addInterceptor(loggingInterceptor)
            }
            val time = (System.currentTimeMillis() / 1000)
            val sign = SignUtil.makeSign(Constant.appid, Constant.appKey, time)
            OkGo.post<String>(url + System.currentTimeMillis())
                    .tag(tag)
                    .cacheMode(CacheMode.NO_CACHE)
                    .retryCount(0)
                    .isMultipart(true)
                    .params("appId", Constant.appid)
                    .params("appSign", sign)
                    .params("appTime", time.toString())
                    .params("channel", channel)
                    .params("packageName", packageName)
                    .params("version", version)
                    .client(builder.build())
                    .execute(object : StringCallback() {
                        override fun onSuccess(response: Response<String>?) {
                            val mjson = response?.body()
                            if (mjson != null) {
                                callback.onSuccess(mjson)
                            } else {
                                callback.onFail("FaildException: response.body() is Null")
                            }
                        }

                        override fun onError(response: Response<String>?) {
                            super.onError(response)
                            callback.onFail("FaildException:code=" + response?.exception.toString())
                        }
                    })

        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
            callback.onFail("UnsupportedEncodingException:" + "msg=" + e.message.toString())
        }
    }

    /**
     * 取消请求
     */
    override fun cancelRequest() {
        OkGo.getInstance().cancelTag(tag)
    }

    /**
     * 保存缓存数据
     */
    override fun saveCache(context: Context, json: String): Boolean {
        return try {
            if (cacheHelper == null) {
                cacheHelper = CacheHelper.getInstance(context, CacheHelper.DBNAME, null, CacheHelper.SQLVERSION)
            }
            cacheHelper!!.setJson(json)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    /**
     *获取缓存数据
     */
    override fun getCache(context: Context): BeanResponse? {
        if (cacheHelper == null) {
            cacheHelper = CacheHelper.getInstance(context, CacheHelper.DBNAME, null, CacheHelper.SQLVERSION)
        }
        try {
            val gao = Gson()
            val mjson = cacheHelper!!.getJson()
            if (mjson != null) {
                return gao.fromJson(mjson, BeanResponse::class.java)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 关闭数据库
     */
    override fun DBClose() {
        cacheHelper?.dbClose()
    }
}